from django.shortcuts import redirect
from rest_framework.views import exception_handler
from rest_framework.exceptions import ValidationError
from rest_framework import status as ResponseStatus

# 自定义异常处理响应，用于在视图中直接抛出异常到这里处理，
# 比如：serializer.is_valid(raise_exception=True)
def custom_exception_handler(exc, context):
    exc.status_code = ResponseStatus.HTTP_200_OK
    response = exception_handler(exc, context)

    if isinstance(exc, ValidationError):
        response.data['code'] = ResponseStatus.HTTP_400_BAD_REQUEST
        response.data['data'] = []
        if isinstance(response.data, dict):
            response.data['message'] = list(dict(response.data).values())[0][0]

            for key in dict(response.data).keys():
                if key not in ['code', 'data', 'message']:
                    response.data.pop(key)
        else:
            response.data['message'] = '输入有误'
        return response

    if response:
        detail = response.data["detail"].code if "detail" in response.data else ""
        response.data.clear()
        response.data['code'] = response.status_code
        response.data['data'] = []

        if response.data["code"] == 404:
            try:
                response.data['message'] = response.data.pop('detail')
            except KeyError:
                response.data['message'] = "未找到"
            # return redirect(STATIC_URL["admin"] + "/#/404")

        elif response.status_code == 400:
            response.data['message'] = '输入错误'

        elif response.status_code == 401:
            response.data['message'] = '未认证'

        elif response.status_code >= 500:
            response.data['message'] = "服务器错误"

        elif response.status_code == 403:
            response.data['message'] = "您没有执行该操作的权限。"

        elif response.status_code == 405:
            response.data['message'] = '请求不允许'

        elif detail == "authentication_failed":
            response.data['code'] = 401
            response.data['message'] = '无效Token'

        elif detail == "not_authenticated":
            response.data['code'] = 401
            response.data['message'] = '未认证'

        elif detail == "throttled":
            response.data['code'] = 502
            response.data['message'] = '请求过快，还没来得及反应，请重新再试'

        else:
            response.data['message'] = '未知错误'

        response.status_code = ResponseStatus.HTTP_200_OK

    return response